package com.example.shiwu;

import static com.example.shiwu.util.ArrayUtil.stringToDouble;
import static com.example.shiwu.util.ContextVariable.DOWN_NAME;
import static com.example.shiwu.util.DataParseUtil.getKVal;
import static com.example.shiwu.util.SocketMergeCallBackUtils.convertUsingLoop;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chaquo.python.PyObject;
import com.chaquo.python.Python;
import com.chaquo.python.android.AndroidPlatform;
import com.example.shiwu.db.model.Alarm;
import com.example.shiwu.db.model.Arrange;
import com.example.shiwu.db.model.BoxElectrodeRo;
import com.example.shiwu.db.model.Device;
import com.example.shiwu.db.model.Items;
import com.example.shiwu.db.model.Sends;
import com.example.shiwu.db.model.User;
import com.example.shiwu.db.vo.MyQueue;
import com.example.shiwu.manager.DatabaseHelper;
import com.example.shiwu.service.AlarmService;
import com.example.shiwu.service.ArrangeService;
import com.example.shiwu.service.BoxElectrodeRoService;
import com.example.shiwu.service.DeviceService;
import com.example.shiwu.service.ItemsService;
import com.example.shiwu.service.ReceiveVolEleService;
import com.example.shiwu.service.SendsService;
import com.example.shiwu.service.UserService;
import com.example.shiwu.util.ByteUtil;
import com.example.shiwu.util.Callback;
import com.example.shiwu.util.DataParseUtil;
import com.example.shiwu.util.FileDownUtil;
import com.example.shiwu.util.SharedPreferencesUtii;
import com.example.shiwu.util.SocketMergeCallBackUtils;

import org.json.JSONException;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.hutool.core.util.IdUtil;

public class SendReceiveAddActivity extends AppCompatActivity {

    private DeviceService deviceService;
    private ItemsService itemsService;
    public ListView editSb;
    public static TextView title_text, title_seting, send_sub_btn, send_pop_status, send_jiance_btn;
    public ImageView title_back;
    private DatabaseHelper dbHelper;
    public static Context myContext;
    private TextView pop_close;
    public int startCount = 0;
    private EditText send_duration_val,
            send_point_a_val, send_point_b_val, send_point_m_val, send_point_n_val, clear_all_mux_box_connect_val;
    private Spinner send_repeat_val, send_frequency_val, send_filter_frequency_val, send_voltage_val;
    private PopupWindow mPopWindow;
    private SendsService sendsService;
    private AlarmService alarmService;
    private ArrangeService arrangeService;
//    private TextView pop_close;

    private final String TAG = "SendReceiveActivity";
    private static final String IP_ADDRESS = "ip_address";
    private static final String CLIENT_PORT = "client_port";
    private static final String CLIENT_MESSAGETXT = "client_msgtxt";

    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor editor;
    private static final int MSG_RECEIVE_DATA = 1;
    private static final int MSG_RECEIVE_DATA_SAVE = 2;
    private static final int MSG_RECEIVE_OVER_DATA = 3;
    private static final int MSG_RECEIVE_TOAST_DATA = 4;
    private static final int MSG_BING_ERROR_DATA = 5;
    private static final int STAR_POP = 6;
    private TextView receive_voltage;
    private Python py;
    private PyObject pyobj, pyobj1, pyplot, pyobj2, pyobj3, pyobjfft;
    private byte[] bytesData;
    private byte[] data, data2, data3;
    private Boolean startGater = false;
    private Boolean myBool = false;
    private Boolean myBool2 = false;
    private Boolean myBool3 = false;
    private Boolean myBool4 = false;
    private Boolean myBool5 = false;
    private String send_piont = "";//发射点
    private String receive_piont = "";//接收点
    private long timeouts = 15000;
//    private Boolean socketListenerBoo = true;

    private Integer rx_voltage_data_len = 0;
    private String simpleUUID = "";
    private String itemsId,uid,sid;
    private String sf = "";
    private String srepeat = "";
    private String svaltage = "";
    private static Integer packet_indx = 0;
    private Integer packet_indx_111 = 0;
    private Boolean bo1 = true;
    private int packet_indx1 = 0;
    public static int packet_indx_old = 0;
    private static Integer packet_lens = 0;
    public static int toatalByte = 0;
    private static int test_cout = 0;
    public static String receiveDataAll = "";
    public ArrayList<byte[]> all_byte_lis;
    public int count_byte = 0;
    private static String cmd_index_len = "";//消息的id 10
    private View contentView;
    private TextView send_voltage_pop_val, send_repeat_pop_val, send_freq_pop_val, receive_duration_pop_val;
    private MyQueue queue, queueMsg, queueRmsMsg;
    private String permutationMode;//采集模式，加到CVS里
    private Integer devtype;//采集模式0-4
    private String deviceId;//设备ID 用于存储ALARM
    private String alarmVal;// alarm内容
    private int msg_sueecss_count = 0;
    public static Boolean receive_one_field_sta = true;
    public static Boolean returnSta = true;
    public int error = 0;
    public int indexsum = 0;
    private ArrayList<String> boxLatLon;
    private int inclickGatherCount;//点击采集按钮次数
    private ReceiveVolEleService receiveVolEleService;
    private UserService userService;
    //private SocketUtils socketUtils;
    private static SocketMergeCallBackUtils socketUtils;
    private String[] clearStrLisAll;
    public static MyThread myThread;
    public static Boolean recv_float_bool = false;
    public int rec_count = 0;
    public Boolean errorSta = false;
    public static Boolean boolErr = true;
    public Boolean recv_float_bool2 = true;
    public Boolean anewSta = true;
    private String userName;
    private String sn;
    private List<String> alis = null;
    private int alisIndx = 0;
    private String[] boxlis = null;

    private String[] freqData, modeData, freqFilterData, repeatData, valtageData;

    private Boolean boo2 = true;
    private MyAdapter mMyAdapter;
    private RecyclerView mRecyclerView;
    private String boxAdr,voltage; //当前box的id
    List<String> mNewsList = new ArrayList<>();
    List<String> roList = new ArrayList<>();
    private BoxElectrodeRoService boxElectrodeRoService;


    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_RECEIVE_DATA:
                    mRecyclerView = contentView.findViewById(R.id.recyclerview);
                    mMyAdapter = new MyAdapter();
                    mRecyclerView.setAdapter(mMyAdapter);
                    LinearLayoutManager layoutManager = new LinearLayoutManager(myContext);
                    mRecyclerView.setLayoutManager(layoutManager);
//                    mNewsList.clear();
                    break;
                case MSG_RECEIVE_DATA_SAVE:
                    Integer indx = (Integer) msg.obj;
                    boxElectrodeRoService = new BoxElectrodeRoService();
                    BoxElectrodeRo boxElectrodeRo = new BoxElectrodeRo();
                    boxElectrodeRo.setBoxId(boxAdr);
                    boxElectrodeRo.setOneRo(mNewsList.get(indx));
                    boxElectrodeRoService.saveOrUpdata(boxElectrodeRo);
                case MSG_RECEIVE_OVER_DATA:
                    send_pop_status.setText("采集电极电阻结束");
                    break;
                case MSG_BING_ERROR_DATA:
                    Toast.makeText(myContext, "设备绑定失败！", Toast.LENGTH_SHORT).show();
                    break;
                case STAR_POP:
                    showPopupWindow();//pop弹框
                    break;
                default:
                    break;
            }
        }

        ;
    };



    @Override
    protected void onDestroy() {
        super.onDestroy();
        //退出HandlerThread的Looper循环。
        System.out.println("---------------------- onDestroy --------------------");
        SocketMergeCallBackUtils.success_count = 0;
        boo2 = false;
        if (socketUtils != null) {
            socketUtils.isReConnect = true;
            socketUtils.releaseSocket();
            socketUtils = null;
        }
        if (myThread != null) {
            myThread.interrupt();
        }
        releaseObj();

    }
     public void releaseObj(){
         contentView = null;
         mPopWindow = null;
         py = null;
         pyobj = null;
         pyobj1 = null;
         pyobjfft = null;
         pyobj2 = null;
         pyobj3 = null;
         myContext = null;
         title_back = null;
         title_text = null;
         title_seting = null;
         receive_voltage = null;
         deviceService = null;
         send_sub_btn = null;
         send_jiance_btn = null;
         userService = null;
         itemsService = null;
     }


    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        setContentView(R.layout.send_receive_add);
        arrangeService = new ArrangeService();
        myContext = this;
        title_back = findViewById(R.id.title_back);
        title_text = findViewById(R.id.title_text);
        title_seting = findViewById(R.id.title_setting);
        title_text.setText("发射接收信息");

        title_seting.setVisibility(View.INVISIBLE);
        receive_voltage = findViewById(R.id.receive_voltage_val);

        send_sub_btn = findViewById(R.id.send_sub_btn);
        send_jiance_btn = findViewById(R.id.send_jiance_btn);
        deviceService = new DeviceService();
        userService = new UserService();
        itemsService = new ItemsService();
        User user = userService.getLoginUser();
        userName = user.getName();
        List<Device> deviceList = deviceService.getDevice(new Device());
        if(deviceList.size()>0){
            sn = deviceList.get(0).getSn();
            String deviceIds = SharedPreferencesUtii.getSharedPreferences("deviceId",myContext);
            if(!deviceIds.equals("")){
                if (userName.equals("user")){
                    if(!deviceIds.equals(sn)){
                        Message msg1 = new Message();
                        msg1.what = MSG_BING_ERROR_DATA;
                        mHandler.sendMessage(msg1);
                        return;
                    }
                }
            }
        }


        Integer boxId = getBoxInx();
        initTextView();

        //HexBinary();
        Resources res = getResources();
        freqData = res.getStringArray(R.array.freqData);
        modeData = res.getStringArray(R.array.modeData);
        repeatData = res.getStringArray(R.array.repeatCount);
        valtageData = res.getStringArray(R.array.valtageData);

        initData();
        title_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SendReceiveAddActivity.this.finish();
            }
        });

        send_sub_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    saveSend();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        send_jiance_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                getTexts();
                                Message msg = new Message();
                                msg.what = STAR_POP;
                                mHandler.sendMessage(msg);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }).start();
            }
        });


        try {
            initPython(this);
            //NetWorkUtil.getApIpAddress2();
            //pyMain();
        } catch (JSONException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    private void initData() {

        Sends sends = new Sends();
        Items items = findSelectItem();
        //sends.setId(1);
        sends.setItemId(items.getId());
        sends.setType(0);
        sendsService = new SendsService();
        //sendsService.updade(sends,new Sends());
        List<Sends> sendlis = sendsService.getSendsLast(sends);
        if (sendlis.size() > 0) {
            send_voltage_val.setSelection(Integer.parseInt(sendlis.get(0).getVoltage()));
            send_repeat_val.setSelection(Integer.parseInt(sendlis.get(0).getRepeatNum()));
            //send_frequency_val.setText(sendlis.get(0).getSendFrequency());
            voltage = valtageData[Integer.parseInt(sendlis.get(0).getVoltage())];
            send_frequency_val.setSelection(Integer.parseInt(sendlis.get(0).getSendFrequency()));
            send_filter_frequency_val.setSelection(Integer.parseInt(sendlis.get(0).getFilterFrequency()));
            uid = sendlis.get(0).getUid();
            sid = String.valueOf(sendlis.get(0).getId());
            //send_duration_val.setText(sendlis.get(0).getSendDuration());
            //clear_all_mux_box_connect_val.setText(sendlis.get(0).getBoxaddr());
        }
    }

    private void initTextView() {
        send_voltage_val = findViewById(R.id.send_voltage_val);
        send_repeat_val = findViewById(R.id.send_repeat_val);
        send_frequency_val = findViewById(R.id.send_frequency_val);
        send_filter_frequency_val = findViewById(R.id.send_filter_frequency_val);
    }

    /**
     * 读取电阻值
     */
    private boolean sendCheckPoleConnect() {
        Boolean boo1 = true;
//        Boolean boo2 = true;

        //for (int i = 0; i < alis.size(); i++) {
        while (boo2) {
            String[] alisOne = alis.get(alisIndx).split(":");
            boxAdr = alisOne[0];
            Log.i("SocketClient", "kCheckPoleConnect = " + new String(alisOne[0]) + " _ " + new String(alisOne[1]) + " _ " + new String(alisOne[2]) + " _ " + new String(alisOne[3]));
            byte[] data = pyobj1.callAttr("CheckPoleConnect", 50, alisOne[0], alisOne[1], alisOne[2], alisOne[3]).toJava(byte[].class);
            String box = new String(alisOne[0]) + " _ " + new String(alisOne[1]) + " _ " + new String(alisOne[2]) + " _ " + new String(alisOne[3]);
            SocketMergeCallBackUtils.writeMsgByteCheckPole(data, new Callback() {
                @Override
                public void onSuccess(byte[] data) {
                    Log.i("SocketClient", "kCheckPoleConnect 7 Text sent successfully============= " + new String(data));
                    String msg = new String(data);
                    if (!msg.equals("")) {
                        if (msg.equals("0,wait;")) {
                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }

                            byte[] myByte = socketUtils.readDataHeadCheckPole();// 消息状态
                            String myByteStr = new String(myByte);
                            if (myByteStr.equals("0,Success;")) {
                                try {
                                    Thread.sleep(1000);
                                    byte[] myBytes = socketUtils.readDataHeadCheckPole();// 消息状态
                                    String myByteStr1 = new String(myBytes);
                                    if (myByteStr1.equals("8,success,")) {
                                        byte[] myByte1 = socketUtils.readData13();
                                        ArrayList<Byte> mydatas = new ArrayList<>();
                                        for (int i = 0; i < 2; i++) {
                                            if (myByte1[i] != 44) {
                                                mydatas.add(myByte1[i]);
                                            } else {
                                                break;
                                            }
                                        }
                                        byte[] b1 = convertUsingLoop(mydatas);
                                        System.out.println(new String(b1));
                                        mNewsList.add(alisIndx+":"+box + ":" +  recv_short(b1));
                                        roList.add(recv_short(b1));
                                        alisIndx++;
                                        Thread.sleep(1000);
                                        mydatas = null;
                                    }
                                } catch (InterruptedException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        } else if (msg.equals("0,Success;")) {
                            try {
                                Thread.sleep(1000);
                                byte[] myByte = socketUtils.readDataHeadCheckPole();// 消息状态
                                String myByteStr = new String(myByte);
                                if (myByteStr.equals("8,success,")) {
                                    byte[] myByte1 = socketUtils.readData13();
                                    ArrayList<Byte> mydata = new ArrayList<>();
                                    for (int i = 0; i < 2; i++) {
                                        if (myByte1[i] != 44) {
                                            mydata.add(myByte1[i]);
                                        } else {
                                            break;
                                        }
                                    }
                                    mNewsList.add(alisIndx+":"+box + ":" + recv_short(convertUsingLoop(mydata)));
                                    roList.add(recv_short(convertUsingLoop(mydata)));
                                    alisIndx++;
                                    Thread.sleep(1000);
                                    mydata = null;
                                }
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }

                        }

                    }
                    Message msg1 = new Message();
                    msg1.what = MSG_RECEIVE_DATA;
                    msg1.obj = alisIndx;
                    mHandler.sendMessage(msg1);
                }

                @Override
                public void onFailure(String errorMessage) {
                    Log.e("SocketClient", "kSetTxWaveWithParam 3 Failed to send text: " + errorMessage);
                }
            });
            if (alisIndx % 11 == 0) {
                Items items = findSelectItem();
                boxElectrodeRoService = new BoxElectrodeRoService();
                BoxElectrodeRo boxElectrodeRo = new BoxElectrodeRo();
                boxElectrodeRo.setItemId(String.valueOf(items.getId()));
                boxElectrodeRo.setBoxId(boxAdr);
                if(roList.size()>0) {
                    boxElectrodeRo.setOneRo(roList.get(0));
                    boxElectrodeRo.setTwoRo(roList.get(1));
                    boxElectrodeRo.setThreeRo(roList.get(2));
                    boxElectrodeRo.setFourRo(roList.get(3));
                    boxElectrodeRo.setFiveRo(roList.get(4));
                    boxElectrodeRo.setSixRo(roList.get(5));
                    boxElectrodeRo.setSevenRo(roList.get(6));
                    boxElectrodeRo.setEightRo(roList.get(7));
                    boxElectrodeRo.setNineRo(roList.get(8));
                    boxElectrodeRo.setTenRo(roList.get(9));
                    boxElectrodeRo.setElevenRo(roList.get(10));
                }
                boxElectrodeRo.setStatus(0);
                boxElectrodeRo.setVoltage(voltage);
                boxElectrodeRoService.saveOrUpdata(boxElectrodeRo);
                roList.clear();
            }
            if (alisIndx == alis.size()) {
                boo2 = false;
                Message msg1 = new Message();
                msg1.what = MSG_RECEIVE_OVER_DATA;
                mHandler.sendMessage(msg1);
                return boo1;
            }

        }

        return boo1;
    }


    /**
     * 查询告警，并写入数据库
     * 1.发送18，get;读取success后截取数据，
     * 2.调用getAlarm13方法 发送13,update;命令
     */
    private void getAlarm18() {
        String data = "18,get;";
        SocketMergeCallBackUtils.writeMsg18(data, new Callback() {
            @Override
            public void onSuccess(byte[] data) {
                Log.i("SocketClient", "Alarm 18 Text sent successfully ============= " + new String(data));
                String msg = new String(data);
                if (!msg.equals("")) {
                    String msglis_18 = ByteUtil.byteTransformAscil(data);
                    //System.out.println("  msglis_18 ===================="+ msglis_18);
                    deviceId = msglis_18.split(",")[1];//固件版本
                    if (!deviceId.equals("")) {
                        //读取success后截取数据，再发送13命令
                        //getAlarm13();
                    }
                }
            }

            @Override
            public void onFailure(String errorMessage) {
                Log.e("SocketClient", "Alarm 18 Failed to send text: " + errorMessage);
            }
        });
    }


    private boolean getStatus(String message) {
        Boolean stabool = false;
        if (message.contains("0,Success;") && !message.equals("")) {
            System.out.println("======================== Success bad_param ================" + message);
            stabool = true;
        } else if (message.contains("0,wait;")) {
            System.out.println("======================== wait bad_param ================" + message);
            stabool = false;
        } else if (message.contains("0,Timeout;")) {
            System.out.println("======================== bad_param ================" + message);
            System.out.println(" kSetMuxBoxConnect switch box connect error ");
            stabool = false;
            String msg1 = "开关盒子连接出错！";
            Message msg = new Message();
            msg.what = MSG_RECEIVE_TOAST_DATA;
            msg.obj = msg1;
            mHandler.sendMessage(msg);
        } else if (message.equals("0,Bad_Param;") || message.equals("0,BadParam;")) {
            System.out.println("======================== bad_param ================" + message);
            stabool = false;
            String msg1 = "ABMN配置错误！";
            Message msg = new Message();
            msg.what = MSG_RECEIVE_TOAST_DATA;
            msg.obj = msg1;
            mHandler.sendMessage(msg);
        } else if (message.equals("0,alarm;")) {
            System.out.println("========================alarm bad_param ================" + message);
            getAlarm18();
            stabool = false;
            String msg1 = "设备告警！";
            Message msg = new Message();
            msg.what = MSG_RECEIVE_TOAST_DATA;
            msg.obj = msg1;
            mHandler.sendMessage(msg);
        } else if (message.equals("None")) {
            System.out.println(" usb/wifi connect error ");
            stabool = false;
        } else if (message.contains("kErrorAlarm")) {//告警写入
            System.out.println(" kErrorAlarm================= " + message);
            Alarm alarm = new Alarm(itemsId);
            alarm.setAlarmMsg(message);
            alarmService.save(alarm);
            stabool = false;
        } else if (message.equals("null")) {
            if (startCount == 1) {
                stabool = false;
                String msg1 = "采集数据失败！";
                Message msg = new Message();
                msg.what = MSG_RECEIVE_TOAST_DATA;
                msg.obj = msg1;
                mHandler.sendMessage(msg);
            }
        }
        return stabool;
    }


    private void saveSend() throws InterruptedException {
        Sends sends = new Sends();
        sends.setVoltage(String.valueOf(send_voltage_val.getSelectedItemPosition()));
        sends.setType(0);
        sends.setStatus(0);
        sends.setErrorPoint("0");
        sends.setErrorPointLine(0);
        sends.setRepeatNum(String.valueOf(send_repeat_val.getSelectedItemPosition()));
        sends.setSendFrequency(String.valueOf(send_frequency_val.getSelectedItemPosition()));
        sends.setFilterFrequency(String.valueOf(send_filter_frequency_val.getSelectedItemPosition()));
        sends.setItemId(Integer.valueOf(itemsId));
        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = new Date(System.currentTimeMillis());
        sends.setCreateTime(sim.format(date));
        sends.setUpdateTime(sim.format(date));

        sendsService = new SendsService();
        Arrange arrange1 = new Arrange();
        arrange1.setItemId(Integer.valueOf(itemsId));
        List<Arrange> arrangeLis = arrangeService.getArrange(arrange1);
        if (arrangeLis.size() == 0) {
            Toast.makeText(myContext, "请先添加排列设计！", Toast.LENGTH_SHORT).show();
            return;
        }

        int countItem = findItemCount();

        if (countItem > 0) {
            Sends sends1 = new Sends();
            sends1.setItemId(Integer.valueOf(itemsId));
            List<Sends> sen = sendsService.getSends(sends1);
            sends1.setType(0);
            sends1.setVoltage(String.valueOf(send_voltage_val.getSelectedItemPosition()));
            voltage = valtageData[send_voltage_val.getSelectedItemPosition()];
            sends1.setRepeatNum(String.valueOf(send_repeat_val.getSelectedItemPosition()));
            sends1.setSendFrequency(String.valueOf(send_frequency_val.getSelectedItemPosition()));
            sends1.setFilterFrequency(String.valueOf(send_filter_frequency_val.getSelectedItemPosition()));
            sends1.setUid(uid);
            if(null != sid){
                sends1.setId(Integer.valueOf(sid));
            }

            boolean bl = sendsService.saveOrUpdata(sends, sends1);
            if (bl) {
                Toast.makeText(myContext, "保存成功！", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(myContext, "请先创建项目！", Toast.LENGTH_SHORT).show();

        }

    }

    private void getTexts() throws InterruptedException {
        test_cout = 0;

        startCount = 1;
        if (socketUtils.socket == null) {
            socketUtils = SocketMergeCallBackUtils.getInstance(myContext);
            Thread.sleep(1000);

        } else {
            System.out.println("------------SendReceive_SocketMergeCallBackUtils.resumeThread()------------");
        }
        myThread = new MyThread();
//        showPopupWindow();//pop弹框
    }

    private Integer findItemCount() {
        itemsService = new ItemsService();
        List<Items> lis = itemsService.getItems(new Items());
        return lis.size();
    }

    class MyThread extends Thread {
        public final Object lock = new Object();
        public boolean threadExit;


        public MyThread() {
            threadExit = false;
        }

        /**
         * 调用这个方法实现暂停线程
         */
        public void pauseThread() {
            threadExit = true;
        }

        /**
         * 调用这个方法实现恢复线程的运行
         */
        public void resumeThread() {
            threadExit = false;
            synchronized (lock) {
                lock.notifyAll();
            }
        }

        public void threadExit() {
            threadExit = true;
        }

        /**
         * 注意：这个方法只能在run方法里调用，不然会阻塞主线程，导致页面无响应
         */
        public void onPause() {
            synchronized (lock) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void run() {

            while (!Thread.currentThread().isInterrupted()) {
                while (!threadExit) {
                    //Byte tmp = socketUtils.read();
                    //Boolean boo2 = sendCheckPoleConnect();
                }
            }
        }
    }

    /**
     * 停止网络资源
     */
    private void stopNetworkResources() {

        // 中断线程
        if (myThread != null) {
            myThread.interrupt();
            try {
                myThread.join(1000); // 等待线程结束，最多1秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            myThread = null;
        }

        // 关闭Socket
        if (socketUtils.socket != null && !socketUtils.socket.isClosed()) {
            try {
                socketUtils.socket.close();
                Log.d("NetworkActivity", "Socket closed");
            } catch (IOException e) {
                Log.e("NetworkActivity", "Failed to close socket", e);
            }
            socketUtils.socket = null;
        }
    }


    private void sendMsgForMcu() {

    }

    /**
     * 保存后的弹框
     */
    private Boolean showPopupWindow() {
        //显示PopupWindow
        View rootview = LayoutInflater.from(myContext).inflate(R.layout.send_receive_add, null);


        //设置contentView
        contentView = LayoutInflater.from(myContext).inflate(R.layout.send_receive_add_pop_dianji, null);
        mPopWindow = new PopupWindow(contentView,
                ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(contentView);
        mPopWindow.setTouchable(true); //设置是否响应触摸事件
        mPopWindow.setFocusable(false);//设置是否能获取焦点（如果控件中药EditText需要设置为true不然无法输入）
        mPopWindow.setOutsideTouchable(false);
        setAlpha(0.2f);


        mPopWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0);

        new Thread(new Runnable() {
            @Override
            public void run() {
                sendCheckPoleConnect();
            }
        }).start();
//        send_voltage_pop_val = contentView.findViewById(R.id.send_voltage_pop_val);
//        send_repeat_pop_val = contentView.findViewById(R.id.send_repeat_pop_val);
//        send_freq_pop_val = contentView.findViewById(R.id.send_freq_pop_val);
//        receive_duration_pop_val = contentView.findViewById(R.id.receive_duration_pop_val);
        send_pop_status = contentView.findViewById(R.id.send_pop_status);

        // 构造一些数据
//        for (int i = 0; i < 50; i++) {
//
//            mNewsList.add("标题标题标题标" + i);
//        }


        pop_close = contentView.findViewById(R.id.send_pop_close);
        pop_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (startCount == 1) {
                    AlertDialog.Builder dialog = new AlertDialog.Builder(myContext);//通过AlertDialog.Builder创建出一个AlertDialog的实例

                    dialog.setTitle("提示");//设置对话框的标题
                    dialog.setMessage("采集电极数据中请勿离开页面,否则会中断采集!");//设置对话框的内容
                    dialog.setCancelable(false);//设置对话框是否可以取消
                    dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {//确定按钮的点击事件

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }

                            mPopWindow.dismiss();
                            setAlpha(1.0f);
                            SendReceiveAddActivity.this.finish();
                        }
                    });
                    dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {//取消按钮的点击事件
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    dialog.show();//显示对话框
                } else {
                    mPopWindow.dismiss();
                    setAlpha(1.0f);
                    SendReceiveAddActivity.this.finish();
                }

            }
        });

        //把背景还原
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                SocketMergeCallBackUtils.success_count = 5;
                setAlpha(1.0f);
            }
        });
        return true;
    }


    private void initPython(Context myContext) throws JSONException, InterruptedException {
        //初始化python环境
        if (!Python.isStarted()) {
            Python.start(new AndroidPlatform(myContext));
        }

        py = Python.getInstance();
        //调用hello_python.py里面的plot函式
        pyobj = py.getModule("plotmy");
        pyobj1 = py.getModule("Send_Param");

    }

    private void setAlpha(float f) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = f;
        getWindow().setAttributes(lp);
    }

    public class ViewHolder {

        public ImageView mChart1;

        public ViewHolder(View view, int position) {
            mChart1 = view.findViewById(R.id.send_pop_chart);

        }

    }

    public int getBoxInx() {
        Items items = findSelectItem();
        itemsId = items.getId().toString();
        Device device = new Device();
        device.setItemId(itemsId);
        List<Device> lis = deviceService.getDevice(device);
        int count = 0;
        if (lis.size() > 0) {
            String box = lis.get(0).getBox().replaceAll(" ", "");
            boxlis = box.split(",");
            alis = new ArrayList();
            for (int y = 0; y < boxlis.length; y++) {
                if (!boxlis[y].equals("00")) {
                    for (int i = 1; i < 12; i++) {
                        String boxAb = boxlis[y] + ":" + i + ":" + boxlis[y] + ":" + (i + 1);
                        alis.add(boxAb);
                    }
                }

            }
        }

        return alis.size();
    }

    private Items findSelectItem() {
        itemsService = new ItemsService();
        Items items = new Items();
        Items items1 = new Items();
        items.setStatus(1);
        List<Items> lis = null;

        try {
            lis = itemsService.getItems(items);
            items1 = lis.get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return items1;
    }


    private Integer recv_unsigned_int(byte[] val) {

        return DataParseUtil.recv_unsigned_int(val);
    }

    private String recv_float(byte[] val) {
        return DataParseUtil.recv_float(val);
    }

    private String recv_short(byte[] val) {
        return DataParseUtil.recv_short(val);
    }

    class MyAdapter extends RecyclerView.Adapter<MyViewHoder> {

        @NonNull
        @Override
        public MyViewHoder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = View.inflate(SendReceiveAddActivity.this, R.layout.dianji_list_item, null);
            MyViewHoder myViewHoder = new MyViewHoder(view);
            return myViewHoder;
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHoder holder, int position) {
            //for (String ss:mNewsList) {
            String[] slit = mNewsList.get(position).split(":");
            holder.mTitleId.setText(slit[0]);
            holder.mTitleTv.setText(slit[1]);
            holder.mTitleVal.setText(slit[2]);
            //}

        }

        @Override
        public int getItemCount() {
            return mNewsList.size();
        }
    }

    class MyViewHoder extends RecyclerView.ViewHolder {
        TextView mTitleTv,mTitleId,mTitleVal;
        TextView mTitleContent;

        public MyViewHoder(@NonNull View itemView) {
            super(itemView);
            mTitleId = itemView.findViewById(R.id.dianjiid);
            mTitleTv = itemView.findViewById(R.id.dianji);
            mTitleVal = itemView.findViewById(R.id.dianjival);
//            mTitleContent = itemView.findViewById(R.id.textView2);
        }

    }

    public static void main(String[] args) {
        byte[] by = {66, 48, 44, 98, 66, 61, 66, 44, 90, -1, 122, -69, 59, 48, 44, 83, 117, 99, 99, 101};
    }

//    public static void main(String[] args) {
//        String str = "0.2883838382828282";
//        BigDecimal bd = stringToDouble(str);
//        BigDecimal bd1 = bd.multiply(BigDecimal.valueOf(100));
//        System.out.println(bd1);
//    }

}